﻿using System;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using TombstoneHelper;
using tumblr.Models;
using tumblr.Models.PostModel;

namespace tumblr.Views
{
    public partial class AllPostsPage : PhoneApplicationPage
    {
        public AllPostsPage()
        {
            InitializeComponent(); 
            
            DataContext = App.AllPostsViewModel;
            Loaded += new RoutedEventHandler(SearchPage_Loaded);
        }

        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            this.SaveState(e);
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            this.RestoreState();
        }

        private void SearchPage_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!App.SearchViewModel.IsDataLoaded)
                App.SearchViewModel.LoadData();
        }

        private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (MainListBox.SelectedIndex == -1)
                return;

            try
            {
                var postLink = ((PostModelBase)(MainListBox.SelectedItem)).Link;

                WebBrowserTask openWebsiteTask = new WebBrowserTask { Uri = new Uri(postLink) };
                openWebsiteTask.Show();
            }
            catch (UriFormatException)
            {
                return;
            }
        }
    }
}